import kk from 'kokos'
import config from 'lotteryConfig'

cc.Class({
    extends: cc.Component,

    onLoad() {
        this.turnBoard = this.node.getChildByName('turnBoard')
        this.lotteryButton = this.node.getChildByName('lotteryButton')

        kk.lottery.init(config)
        this.initBoardView()
    },

    start() {

    },

    initBoardView() {
        const lotteryItems = this.turnBoard.children
        const partAngle = 360 / lotteryItems.length

        for (let i = 0; i < lotteryItems.length; i++) {
            const item = lotteryItems[i]
            const iconNode = item.getChildByName('icon')
            const labelNode = item.getChildByName('label')
            const iconUrl = config[i].img
            const value = config[i].value

            item.angle = partAngle * (i + 1) - partAngle / 2
            cc.loader.loadRes(iconUrl, cc.SpriteFrame, (err, sp) => {
                if (err) {
                    cc.log(err)
                    return
                }
                iconNode.getComponent(cc.Sprite).spriteFrame = sp
            })

            labelNode.getComponent(cc.Label).string = `x ${value}`
        }

    },

    handleLottery() {
        const rotateTimeS = 3
        const rotateRound = 5
        const numOfAward = config.length
        const awardIndex = kk.lottery.getAwardIndex()
        // console.log(config[awardIndex])

        const partAngle = 360 / numOfAward
        const boardAngle = config[awardIndex].id * partAngle - 0.5 * partAngle

        const rotateAction = cc.rotateBy(rotateTimeS, boardAngle + 360 * rotateRound).easing(cc.easeSineInOut())
        const finished = cc.callFunc(() => {
            this.lotteryButton.active = true
            const award = config[awardIndex]
            const bd = kk.baseData
            if (award.type == 'gold') {
                bd.setGold(bd.getGold() + award.value)
            }
        }, this)
        const seq = cc.sequence(rotateAction, finished)

        this.turnBoard.angle = 0
        this.lotteryButton.active = false
        this.turnBoard.runAction(seq)

    },

    handleClose() {
        this.node.destroy()
    }

    // update (dt) {},
});
